$(function () {
    $(document).keydown(function (e) {
        var keycode = e.keyCode;
        if (keycode == 13) {
            $("#btnSearch").click();
        }
    });

    $(document).delegate("#btnSearch", "click", function () {
        reflashTable();
    });
});


//用户列表===========================================================================================================


function initUserTable() {
    var url = "/manage/user/list";
    $('#table').bootstrapTable({
        url: url,
        striped: true,
        cache: false,
        pagination: true,
        sidePagination: "server",
        toolbar: "#toolbar",
        pageList: [10, 25, 50, 100],
        columns: [{
            checkbox: true,
            align: 'center',
        }, {
            field: 'userId',
            title: '用户 ID'
        }, {
            field: 'userName',
            title: '用户名称'
        }, {
            field: 'status',
            title: '状态',
            formatter: function (value, row, index) {
                if ("1" == value) {
                    return '<span class="label label-success" style="font-size:12px;">上线</span>';
                    return "上线";
                } else {
                    return '<span class="label label-default" style="font-size:12px;">下线</span>';
                    return "下线";
                }
            }
        }, {
            field: 'startTime',
            title: '账号有效期',
            formatter: function (value, row) {
                var startTime = row.startTime;
                var endTime = row.endTime;
                if ($.isEmptyObject(startTime) && $.isEmptyObject(endTime)) {
                    return "";
                } else if (!$.isEmptyObject(startTime) && $.isEmptyObject(endTime)) {
                    return startTime + " ~ 无限期";
                } else if ($.isEmptyObject(startTime) && !$.isEmptyObject(endTime)) {
                    return "截止到" + endTime;
                }
                return startTime + " ~ " + endTime;
            }
        }, {
            field: 'roleNames',
            title: '角色'
        }, {
            field: 'lastLoginTime',
            title: '最后登录时间',
            sortable: true
        }, {
            field: 'areaName',
            title: '归属地'
        }, {
            field: 'scopeNames',
            title: '数据权限'
        }, {
            field: 'userId',
            title: '操作',
            formatter: function (value, row) {
                var result = "";
                if (modifyFlag) {
                    result += "<a href='javascript:Base.dialogIframe(\"用户查看\" ,\"/manage/user/view/@userId\")' class='btn btn-xs'><span class='glyphicon glyphicon-info-sign'></span> 查看</a>";
                    result += "<a href='javascript:Base.dialogIframe(\"用户编辑\" ,\"/manage/user/modify/@userId\")' class='btn btn-xs'><span class='glyphicon glyphicon-pencil'></span> 编辑</a>";
                    result += "<a href='javascript:userPwdRestDialog(\"@userId\", \"@userName\")' class='btn btn-xs text-danger'><span class='glyphicon glyphicon-lock'></span> 重置密码</a>";
                    result += "<a href='javascript:userRoleConfig(\"@userId\")' class='btn btn-xs'><span class='iconfont icon-shejishi'></span> 角色配置</a>";
                }
                if (deleteFlag) {
                    result += "<a href='javascript:userDeleteDialog(\"@userId\", \"@userName\")' class='btn btn-xs text-danger'><span class='glyphicon glyphicon-remove'></span> 删除</a>";
                }

                result = result.replace(/@userId/g, value);
                result = result.replace(/@userName/g, row.userName);

                return result;
            }
        }],
        responseHandler: function (res) {
            addFlag = res.data.addFlag;
            modifyFlag = res.data.modifyFlag;
            deleteFlag = res.data.deleteFlag;
            uploadFlag = res.data.uploadFlag;
            downloadFlag = res.data.downloadFlag;

            return res.data;
        },
        queryParams: function (params) {
            var searchkey = $.trim($("#searchkey").val());
            var status = $("#status").val();
            var temp = {
                pageSize: params.limit,
                pageNum: (params.offset / params.limit) + 1,
                sort: params.sort,
                searchkey: searchkey,
                status: status
            };
            return temp;
        }
    });
}

function reflashTable() {
    $("#table").bootstrapTable('refresh');
}

function userDeleteDialog(userId, userName) {
    BootstrapDialog.show({
        title: '删除确认',
        message: '请再次确认是否删除用户【' + userName + '】',
        type: BootstrapDialog.TYPE_DANGER,
        buttons: [{
            label: '确定',
            cssClass: 'btn-danger',
            action: function (dialog) {
                userDelete(userId);
                dialog.close();
            }
        }, {
            label: '取消',
            action: function (dialog) {
                dialog.close();
            }
        }]
    });
}

function userPwdRestDialog(userId, userName) {
    BootstrapDialog.show({
        title: '密码确认',
        message: '请再次确认是否重置用户【' + userName + '】的密码为初始密码【' + DEFAULT_PASSWORD + "】",
        type: BootstrapDialog.TYPE_DANGER,
        buttons: [{
            label: '确定',
            cssClass: 'btn-danger',
            action: function (dialog) {
                userPwdRest(userId);
                dialog.close();
            }
        }, {
            label: '取消',
            action: function (dialog) {
                dialog.close();
            }
        }]
    });
}

function onlineBatchDialog() {
    var selections = $('#table').bootstrapTable('getSelections');
    if (selections.length == 0) {
        tiperror("请选择需要上线的用户！");
        return;
    }

    BootstrapDialog.show({
        title: '批量上线确认',
        message: '请再次确认是否进行批量上线操作？',
        type: BootstrapDialog.TYPE_DANGER,
        buttons: [{
            label: '确定',
            cssClass: 'btn-danger',
            action: function (dialog) {
                userOnline();
                dialog.close();
            }
        }, {
            label: '取消',
            action: function (dialog) {
                dialog.close();
            }
        }]
    });
}

function offlineBatchDialog() {
    var selections = $('#table').bootstrapTable('getSelections');
    if (selections.length == 0) {
        tiperror("请选择需要下线的用户！");
        return;
    }

    BootstrapDialog.show({
        title: '批量下线确认',
        message: '请再次确认是否进行批量下线操作？',
        type: BootstrapDialog.TYPE_DANGER,
        buttons: [{
            label: '确定',
            cssClass: 'btn-danger',
            action: function (dialog) {
                userOffline();
                dialog.close();
            }
        }, {
            label: '取消',
            action: function (dialog) {
                dialog.close();
            }
        }]
    });
}

function exportDialog() {
    BootstrapDialog.show({
        title: '导出确认',
        message: '请再次确认是否进行导出操作？',
        type: BootstrapDialog.TYPE_DANGER,
        buttons: [{
            label: '确定',
            cssClass: 'btn-danger',
            action: function (dialog) {
                var searchkey = $.trim($("#searchkey").val());
                var status = $("#status").val();
                var param = {
                    searchkey: searchkey,
                    status: status
                };
                Base.executeExport("/manage/user/export", param);
                dialog.close();
            }
        }, {
            label: '取消',
            action: function (dialog) {
                dialog.close();
            }
        }]
    });
}

function userRoleConfig(userId) {
    var roleTreeHeight = $(window).height() * 0.5;
    userRoleConfigDialog = BootstrapDialog.show({
        title: '角色配置',
        message: $("<p class='alert alert-info manage-user-role-dialog'>共<span id='roleTotalNum' class='label label-primary'>0</span>个角色，已分配<span id='roleSelNum' class='label label-primary'>0</span>个，目前已选中<span id='roleCheckNum' class='label label-danger csp' onclick='openCheckZode()'>0</span>个</p><div id='roleTree' class='ztree loading' style='max-height:" + roleTreeHeight + "px; overflow: auto;'></div>"),
        type: BootstrapDialog.TYPE_PRIMARY,
        buttons: [{
            label: '确定',
            cssClass: 'btn-primary',
            action: function (dialog) {
                saveUserRole(userId);
            }
        }, {
            label: '取消',
            action: function (dialog) {
                dialog.close();
            }
        }],
        onshown: function () {
            queryRoles(userId);
            hideLoading("#roleTree");
        }
    });
}

function queryRoles(userId) {
    Base.ajax({
        "url": "/manage/user/roles/" + userId,
        "async": false,
        "success": function (data) {
            if (data.code) {
                initRoles(data.data.roles);
                $("#roleTotalNum").html(data.data.roleTotalNum);
                $("#roleSelNum").html(data.data.roleSelNum);
                $("#roleCheckNum").html(data.data.roleSelNum);
            } else {
                tiperror("初始化角色信息失败，请刷新页面！");
            }
        }
    });
}

function initRoles(data) {
    var zNodes = data;
    if (true) {
        for (var i = zNodes.length - 1; i >= 0; i--) {
            var z = zNodes[i];
            if (z.type == "role") {
                z.name = '<i class="iconfont icon-shejishi"></i> ' + z.name;
                z.name = z.name + " [" + z.id + "]";
            }
        }
    }
    var setting = {
        view: {
            showIcon: false,
            nameIsHTML: true,
            showTitle: false,
            showLine: false
        },
        check: {
            enable: true
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        callback: {
            onCheck: function (event, treeId, treeNode) {
                $("#roleCheckNum").html(ztree_role.getCheckedNodes(true).length);
            }
        }
    };

    ztree_role = $.fn.zTree.init($("#roleTree"), setting, zNodes);
}

function saveUserRole(userId) {
    var nodes = ztree_role.getCheckedNodes(true);

    var jId = [];
    for (var i = nodes.length - 1; i >= 0; i--) {
        var j = nodes[i];
        if (j.type == "role") {
            jId.push(j.id);
        }
    }

    var data = {
        users: userId,
        roles: jId.join(";")
    };

    Base.ajax({
        "url": "/manage/auth/add/userrole",
        "async": false,
        "data": data,
        "success": function (data) {
            if (data.code) {
                tipsuccess("保存成功");
                userRoleConfigDialog.close();
                reflashTable();
            } else {
                tiperror("保存失败");
            }
        }
    });
}

/**
 * 展开选中的节点
 */
function openCheckZode() {
    var nodes = ztree_role.getCheckedNodes(true);

    var ns = [];
    for (var i = nodes.length - 1; i >= 0; i--) {
        ns = ns.concat(nodes[i].getPath());
    }
    for (var i = ns.length - 1; i >= 0; i--) {
        ztree_role.expandNode(ns[i], true, false, true);
    }
}


//用户新增修改===========================================================================================================


function initUserAddPage() {
    initLaydate();

    initBootstrapValidator(userAdd);

    initAreaSelect();

    initRoleSelect();
}

function initUserModifyPage() {
    initLaydate();

    initBootstrapValidator(userModify, "modify");

    initAreaSelect();

    initRoleSelect();
}

/**
 * 初始化日期控件
 *
 * @Author wucm
 * @Date 2018/1/6
 */
function initLaydate() {
    laydate.render({
        elem: '#startTime'
    });

    laydate.render({
        elem: '#endTime'
    });
}

function initBootstrapValidator(submitFunc, type) {
    var option = {
        message: 'This value is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            userId: {
                message: '用户名验证失败',
                validators: {
                    notEmpty: {
                        message: '用户ID不能为空'
                    },
                    stringLength: {
                        min: 6,
                        max: 30,
                        message: '用户名长度必须在6到30之间'
                    },
                    threshold: 6, //有6字符以上才发送ajax请求
                    remote: { //{"valid",true}代表有效，{"valid",false}代表无效，
                        url: '/manage/user/checkexist',
                        message: '用户已存在',
                        delay: 2000,
                        type: 'POST'
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9_]+$/,
                        message: '用户名由数字字母下划线和.组成'
                    }
                }
            },
            userName: {
                validators: {
                    notEmpty: {
                        message: '用户名称不能为空'
                    }
                }
            }
        }
    };

    if (type == "modify") {
        delete option.fields.userId;
    }

    $('form').bootstrapValidator(option).on('success.form.bv', function (e) {
        e.preventDefault();
        submitFunc();
    });

    $('#resetBtn').click(function () {
        $('form').data('bootstrapValidator').resetForm(true);
    });
}

function initAreaSelect() {
    Base.ajax({
        "url": "/common/areas",
        "success": function (data) {
            if (data.code) {
                var _o = $("#areaId");
                var arr = [];
                $.each(data.data, function (i, item) {
                    arr.push("<option value='" + item.id + "'>" + item.name + "</option>");
                });
                _o.empty().append(arr.join(""));
                areaSelect = _o.select2({
                    placeholder: "请选择归属地",
                });
                if (selAreaId) {
                    areaSelect.val(selAreaId).trigger("change");
                }
            } else {
                tiperror("初始化归属地信息失败！");
            }
        }
    });
}

function initRoleSelect() {
    Base.ajax({
        "url": "/common/roles",
        "success": function (data) {
            if (data.code) {
                var _o = $("#roleIds");
                var arr = [];
                $.each(data.data, function (i, item) {
                    arr.push("<option value='" + item.id + "'>" + item.name + "</option>");
                });
                _o.empty().append(arr.join(""));
                roleSelect = _o.select2({
                    placeholder: "请选择角色，可以选择多个",
                    closeOnSelect: false, // 选中后关闭，false为连续多选
                    maximumSelectionLength: 5, //限制选中的个数
                    tags: false //可以手动添加，若限制手动添加，设置为false
                });
                if (selRoleIds) {
                    roleSelect.val(selRoleIds).trigger("change");
                }
            } else {
                tiperror("初始化角色信息失败！");
            }
        }
    });
}


//ajax提交===========================================================================================================


function userAdd() {
    var data = $('form').serializej();
    if (data.roleIds instanceof Array) {
        data.roleIds = data.roleIds.join(",");
    }

    Base.ajax({
        "url": "/manage/user/add",
        "data": data,
        "success": function (data) {
            if (data.code && data.data == 1) {
                tipsuccess("用户新增成功！");
                if (top.bootstrapDialogIframe) {
                    top.bootstrapDialogIframe.close();
                }
                if (top.reflashTable) {
                    top.reflashTable();
                }
            } else {
                tiperror("用户新增失败！");
            }
        }
    });
}

function userModify() {
    var data = $('form').serializej();
    if (data.roleIds instanceof Array) {
        data.roleIds = data.roleIds.join(",");
    }

    Base.ajax({
        "url": "/manage/user/modify",
        "data": data,
        "success": function (data) {
            if (data.code && data.data == 1) {
                tipsuccess("用户修改成功！");
                if (top.bootstrapDialogIframe) {
                    top.bootstrapDialogIframe.close();
                }
                if (top.reflashTable) {
                    top.reflashTable();
                }
            } else {
                tiperror("用户修改失败！");
            }
        }
    });
}

function userDelete(userId) {
    Base.ajax({
        "url": "/manage/user/delete",
        "data": {
            "userId": userId
        },
        "success": function (data) {
            if (data.code && data.data == 1) {
                tipsuccess("用户删除成功！");
                if (top.bootstrapDialogIframe) {
                    top.bootstrapDialogIframe.close();
                }
                if (top.reflashTable) {
                    top.reflashTable();
                }
            } else {
                tiperror("用户删除失败！");
            }
        }
    });
}

function userPwdRest(userId) {
    Base.ajax({
        "url": "/manage/user/pwdreset",
        "data": {
            "userId": userId
        },
        "success": function (data) {
            if (data.code && data.data == 1) {
                tipsuccess("用户密码重置成功！");
                reflashTable();
            } else {
                tiperror("用户密码重置失败！");
            }
        }
    });
}

function userOnline() {
    var selections = $('#table').bootstrapTable('getSelections');
    if (selections.length == 0) {
        tiperror("请选择需要上线的用户！");
        return;
    }

    var userIds = [];
    $.each(selections, function (id, item) {
        userIds.push(item.userId);
    });
    userIds = userIds.join(",");

    Base.ajax({
        "url": "/manage/user/online",
        "data": {
            "userIds": userIds
        },
        "success": function (data) {
            if (data.code && data.data == 1) {
                tipsuccess("批量上线成功！");
                reflashTable();
            } else {
                tiperror("批量上线失败！");
            }
        }
    });
}

function userOffline() {
    var selections = $('#table').bootstrapTable('getSelections');
    if (selections.length == 0) {
        tiperror("请选择需要下线的用户！");
        return;
    }

    var userIds = [];
    $.each(selections, function (id, item) {
        userIds.push(item.userId);
    });
    userIds = userIds.join(",");

    Base.ajax({
        "url": "/manage/user/offline",
        "data": {
            "userIds": userIds
        },
        "success": function (data) {
            if (data.code && data.data == 1) {
                tipsuccess("批量下线成功！");
                reflashTable();
            } else {
                tiperror("批量下线失败！");
            }
        }
    });
}

